package com.cloudauth.core.intercepter;

import com.cloudauth.core.vo.User;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
@description 当项目中服务与服务适用RestTemplate方式进行访问时适用此配置文件
@author wbs
**/
public class RestTemplateUserContextInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        User user = UserContextHolder.currentUser();

        httpRequest.getHeaders().add("x-user-id", user.getUserId());
        httpRequest.getHeaders().add("x-user-name",user.getUserName());
        httpRequest.getHeaders().add("x-user-serviceName",httpRequest.getURI().getHost());

        return clientHttpRequestExecution.execute(httpRequest,bytes);
    }
}
